/**
 * Module dependencies
 */
var pomelo = require('pomelo');
var fs = require('fs');
var util = require('util');
var consts = require('../consts/consts');
var utils = require('../util/utils');
var userDao = require('../dao/userDao');

var client = pomelo.app.get('redisUser');
var log = console.log;

var exp = module.exports;

var gDataDir = './app/data/';
var gGlobalFile = 'global.json';
var gGlobalInfo = null;


// init
exp.initDataFromFile = function () {
    if (gGlobalInfo) {
        return;
    }
    var tmpGFile = gDataDir + gGlobalFile;
    try {
        fs.openSync(tmpGFile, 'r');
        gGlobalInfo = require('../data/' + gGlobalFile);
    }
    catch (_) {
        gGlobalInfo = { gPlayerId: 0, playerInfoDict: {} };
        try {
            // var tmpStr = util.inspect(gGlobalInfo, {depth: null});
            var tmpStr = JSON.stringify(gGlobalInfo);
            fs.writeFileSync(tmpGFile, tmpStr);
        }
        catch (ex) {
            console.error(tmpGFile + ' is not saved!');
        }
    }

    this.isSavingMutex = false;
};

exp.getPlayerId = function (data) {
    var playerName = data.playerName;
    var password = data.password;
    utils.myPrint('data = ', JSON.stringify(data));

    var d = gGlobalInfo.playerInfoDict;
    if (d[playerName]) {
        var obj = d[playerName];
        if (password === obj.password) {
            return parseInt(obj.playerId);
        }
        else {
            return 0;
        }
    }

    gGlobalInfo.gPlayerId++;
    d[playerName] = {
        password: data.password,
        playerId: gGlobalInfo.gPlayerId
    };

    var self = this;
    if (!self.isSavingMutex) {
        self.isSavingMutex = true;

        var tmpGFile = gDataDir + gGlobalFile;
        // var tmpStr = util.inspect(gGlobalInfo, {depth: null});
        var tmpStr = JSON.stringify(gGlobalInfo);
        fs.writeFile(tmpGFile, tmpStr, function () {
            self.isSavingMutex = false;
        });
    }

    return gGlobalInfo.gPlayerId;
};

/**
 * 校验用户id 和token 是否匹配
 * in: {playerId, gameId, token}
 * out: true || false
 */
exp.checkPlayer = function (msg, cb) {

    var onlineUser = 'onlineGameUser';
    var playerId = parseInt(msg.playerId) || 0;
    var gameId = parseInt(msg.gameId);

    client.hget(onlineUser, playerId, function (err, rel) {
        if (err) {
            log(err);
            cb(err);
            return;
        }
        if (rel === null || parseInt(rel) === 0) {
            cb(null);
            return;
        }
        if (parseInt(rel) !== gameId) {
            log('已经在其它游戏登录，请先从其它游戏退出！');
            cb('已经在其它游戏登录，请先从其它游戏退出！');
            return;
        }
        cb(null);
    });

    return 0;

    // var playerId = msg.playerId || 0;
    // var token = msg.token || '';
    // // data:{playerId, gameId, token}
    // // do check login here
    // var sql = 'select userId, userName from game_user where userId = ? and token = ?',
    //     args = [playerId, token];

    // // var sql = 'select userId, userName from game_user',
    // // 	args = [];

    // userDao.query(sql, args, function (err, rel) {
    //     console.log('rel mysql >>>>>>>>>>>>>>>>>>>>>>>>>>');

    //     if (err) {
    //         cb(err);
    //         return;
    //     }

    //     if (rel.length > 0) {
    //         cb('');
    //     }
    //     else {
    //         cb('can not find player: Id:' + playerId + ' from dataBase!');
    //     }
    // });

};
